package test;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
public class AccessPersonConstructors {
    public static void main(String[] args) {
        /**
         * 示例7
         */
        try {
            Class clz=Class.forName("com.bdqn.pojo.Person");
            Object obj=clz.newInstance();
            System.out.println(obj);
            //获取Person的无参构造
            Constructor c1=clz.getDeclaredConstructor();
            //Person的无参构造为public,这里可以直接访问
            obj=c1.newInstance();
            System.out.println(obj);
            //获取Person的单参构造
            Constructor c2=clz.getDeclaredConstructor(String.class);
            //Person的单参构造为private,这里不能直接访问
            //通过setAccessable方法设置为可访问
            c2.setAccessible(true);
            obj=c2.newInstance("New Person");
            System.out.println(obj);
            Constructor c3=clz.getDeclaredConstructor(String.class,int.class,String.class,String.class);
            //通过setAccessible方法设置为可访问
            c3.setAccessible(true);
            obj=c3.newInstance("New Person",30,"beijing","Hello");
            System.out.println(obj);
        } catch (ClassNotFoundException e) {
          e.printStackTrace();
        } catch (InvocationTargetException e) {
         e.printStackTrace();
        } catch (InstantiationException e) {
         e.printStackTrace();
        } catch (IllegalAccessException e) {
          e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }


        /**
         * 示例6
         */
        //测试反射调用构造方法
        /*try {
            Class clz=Class.forName("com.bdqn.pojo.Person");
            Object obj=clz.newInstance();
            System.out.println(obj);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }*/
    }
}
